package com.alks.function.service.impl.chengKong;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.alks.common.data.thread.UserIdThread;
import com.alks.common.utils.DateUtils;
import com.alks.common.utils.ImageUtils;
import com.alks.common.utils.UserInfoUtil;
import com.alks.common.utils.beanutils.BeanUtil;
import com.alks.common.utils.beanutils.ObjectUtils;
import com.alks.common.utils.excelUtils.ExcelPoiUtils;
import com.alks.common.utils.excelUtils.ExcelUtils;
import com.alks.entity.data.entity.PcCutLotPriceDetail;
import com.alks.entity.data.entity.PcCutLotPriceDetailO;
import com.alks.entity.data.entity.PcCutPriceDetail;
import com.alks.entity.data.entity.PcCutPriceDetailO;
import com.alks.entity.data.enums.chengkong.DefineEnum;
import com.alks.entity.data.page.PageRecord;
import com.alks.entity.data.response.ResponseInfo;
import com.alks.entity.exception.ServiceErrorException;
import com.alks.function.data.dto.chengKong.cost.*;
import com.alks.function.data.dto.chengKong.export.PunchingExportVo;
import com.alks.function.data.dto.chengKong.produce.StyleDetailDto;
import com.alks.function.data.request.chengKong.LotNoRequest;
import com.alks.function.data.request.chengKong.StyleNoRequest;
import com.alks.function.data.request.chengKong.StyleNoToColorRequest;
import com.alks.function.data.request.chengKong.cost.LotNoCutPriceRequest;
import com.alks.function.data.request.chengKong.cost.UpdatePcCutPriceDetail0Request;
import com.alks.function.data.request.chengKong.cost.UpdatePcCutPriceDetailRequest;
import com.alks.function.data.request.chengKong.cost.generateCutLotNoPriceRequest;
import com.alks.function.mapper.chengKong.CostAssignmentMapper;
import com.alks.function.mapper.chengKong.PcLotHeadMapper;
import com.alks.function.mapper.pcfactorywork.PcOutListPriceMapper;
import com.alks.function.service.chengKong.CostAssignmentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.core.io.ClassPathResource;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CostAssignmentServiceImpl implements CostAssignmentService {

    @Resource
    private CostAssignmentMapper costAssignmentMapper;

    /**
     * 选择型体查询
     * @param request
     * @param choose
     * @return
     */
    @Override
    public ResponseInfo SelectTypeList(StyleNoRequest request, Integer choose) {
        PageRecord<StyleDetailDto> list = new PageRecord<>();
        try {
            if (request.getPageNum() == null || request.getPageSize() == null) {
                request.setPageNum(1);
                request.setPageSize(10);
            }
            PageHelper.startPage(request.getPageNum(), request.getPageSize());
            request.setCompanyId(UserIdThread.get().getCompanyId());
            List<StyleDetailDto> dtoList;
            switch (choose) {
                case 1:
                    dtoList = costAssignmentMapper.getSelectTypeList(request);
                    break;
                case 2:
                    dtoList = costAssignmentMapper.getSelectTypeList2(request);
                    break;
                default:
                    return ResponseInfo.error("参数错误!");
            }
            list.setList(dtoList);
            PageInfo pageInfo = new PageInfo(dtoList);
            list.setTotal(pageInfo.getTotal());
            return ResponseInfo.ok(list);
        } catch (DataAccessException e) {
            log.error("数据库访问异常：" + e.getMessage());
            return ResponseInfo.error("数据访问异常");
        } catch (IllegalArgumentException e) {
            log.error("参数异常：" + e.getMessage());
            return ResponseInfo.error("参数异常");
        } catch (Exception e) {
            log.error("处理请求时出错：" + e.getMessage());
            return ResponseInfo.error("处理请求时出错");
        }
    }

    /**
     * 型体资料查询
     * @param request
     * @return
     */
    @Override
    public ResponseInfo TypeInformationList(StyleNoRequest request,Integer choose) {
        PageRecord<StyleDetailToFlagDto> list = new PageRecord<>();
        try {
            if (request.getPageNum() == null || request.getPageSize() == null) {
                request.setPageNum(1);
                request.setPageSize(10);
            }
            PageHelper.startPage(request.getPageNum(), request.getPageSize());
            request.setCompanyId(UserIdThread.get().getCompanyId());
            List<StyleDetailToFlagDto> dtoList;
            switch (choose) {
                case 1:
                    dtoList = costAssignmentMapper.getTypeInformationList(request);
                    break;
                case 2:
                    dtoList = costAssignmentMapper.getTypeInformationList2(request);
                    break;
                default:
                    return ResponseInfo.error("参数错误!");
            }
            list.setList(dtoList);
            PageInfo pageInfo = new PageInfo(dtoList);
            list.setTotal(pageInfo.getTotal());
            return ResponseInfo.ok(list);
        } catch (DataAccessException e) {
            log.error("数据库访问异常：" + e.getMessage());
            return ResponseInfo.error("数据访问异常");
        } catch (IllegalArgumentException e) {
            log.error("参数异常：" + e.getMessage());
            return ResponseInfo.error("参数异常");
        } catch (Exception e) {
            log.error("处理请求时出错：" + e.getMessage());
            return ResponseInfo.error("处理请求时出错");
        }
    }

    /**
     * 冲裁型体单价明细查询
     * @param request
     * @return
     */
    @Override
    public ResponseInfo UnitPriceOfPunchingType(StyleNoToColorRequest request) {
        if (ObjectUtils.isEmpty(request.getStyleNo())||ObjectUtils.isEmpty(request.getStyleColor())){
            return ResponseInfo.error("型体或颜色不能为空!");
        }
        HashMap map = new HashMap();
        String companyId = UserIdThread.get().getCompanyId();
        List<PcCutPriceDetailDto> detailDto = costAssignmentMapper.getUnitPriceOfPunchingType(request.getStyleNo(),request.getStyleColor(),companyId);
        //冲裁单价总数
        BigDecimal totalCutPrice = BigDecimal.ZERO;
        //版数单价总数
        BigDecimal plateNumberPrice = BigDecimal.ZERO;
        if (!ObjectUtils.isEmpty(detailDto)){
            for (PcCutPriceDetailDto t : detailDto) {
                if (!ObjectUtils.isEmpty(t.getCutPrice())) {
                    totalCutPrice=totalCutPrice.add(t.getCutPrice());
                    BigDecimal result = t.getCutPrice().divide(new BigDecimal(2));
                    if (!ObjectUtils.isEmpty(t.getPieceNum())){
                        plateNumberPrice = plateNumberPrice.add(result.multiply(t.getPieceNum()));
                    }
                }
            }
        }
        totalCutPrice = totalCutPrice.setScale(5, RoundingMode.HALF_UP);
        map.put("detailDto",detailDto);
        map.put("sum",totalCutPrice);
        map.put("plateNumberPrice",plateNumberPrice);
        return ResponseInfo.ok(map);
    }

    /**
     * 取数
     * @param request
     * @return
     */
    @Override
    public ResponseInfo fetchList(StyleNoToColorRequest request) {
        if (ObjectUtils.isEmpty(request.getStyleNo())||ObjectUtils.isEmpty(request.getStyleColor())){
            return ResponseInfo.error("请选择型体/颜色!");
        }
        if ("Y".equals(request.getCfmFlag())){
            return ResponseInfo.error("该型体已检核!");
        }
        UserInfoUtil.UserInfo u = UserInfoUtil.getUserInfo();
        Integer detailExist = costAssignmentMapper.getPcCutPriceDetailExist(request.getStyleNo(), request.getStyleColor(),u.getCompanyId());
        if (detailExist!=null&&detailExist>0){
            return ResponseInfo.error("该型体冲裁明细已存在!");
        }
        String flag = pcOutListPriceMapper.getSdStyleProcessHead(request.getStyleNo(), request.getStyleColor(),u.getCompanyId());
        if (!"Y".equals(flag)) {
            return ResponseInfo.error("该型体工艺未检核!");
        }
        List<SdStyleProcessNewDto> newToBlankingList = costAssignmentMapper.getSdStyleProcessNewToBlankingList(request.getStyleNo(), request.getStyleColor(),u.getCompanyId());
        List<PcCutPriceDetail> list=new ArrayList<>();
        if (!ObjectUtils.isEmpty(newToBlankingList)){
            for (SdStyleProcessNewDto t : newToBlankingList) {
                PcCutPriceDetail pcCutPriceDetail = new PcCutPriceDetail();
                BeanUtil.copyProperties(t,pcCutPriceDetail);
                pcCutPriceDetail.setCompanyId(u.getCompanyId());
                pcCutPriceDetail.setSysDate(LocalDateTime.now());
                pcCutPriceDetail.setSysUser(u.getUserName());
                BigDecimal cutNum = getCutNum(t.getPieceNum(), t.getCutLayer());
                pcCutPriceDetail.setCutNum(cutNum);
                list.add(pcCutPriceDetail);
            }
        }
        if (!ObjectUtils.isEmpty(list)){
            //重新排序
            for (int i = 0; i < list.size(); i++) {
                list.get(i).setSeqNo(new BigDecimal(i+1));
            }
            costAssignmentMapper.addPcCutPriceDetail(list);
        }
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 计算cutNum
     * @param pieceNum 片数
     * @param cutLayer 层数
     * @return
     */
    private BigDecimal getCutNum(BigDecimal pieceNum,BigDecimal cutLayer) {
        if (pieceNum!=null&& cutLayer!=null){
            BigDecimal cutNum = pieceNum.divide(cutLayer,5,RoundingMode.HALF_UP);
            return cutNum;
        }else {
            return null;
        }
    }

    /**
     * 删除
     * @param request
     * @return
     */
    @Override
    public ResponseInfo deletePcCutPriceDetail(StyleNoToColorRequest request,Integer choose) {
        if (ObjectUtils.isEmpty(request.getStyleNo())||ObjectUtils.isEmpty(request.getStyleColor())){
            return ResponseInfo.error("型体/颜色不能为空!");
        }
        if (!ObjectUtils.isEmpty(request.getCfmFlag())){
            if (request.getCfmFlag().equals(DefineEnum.CHECKOUT_FLAG.getValue())){
                return ResponseInfo.error("该型体资料已经检核,不能删除!");
            }
        }
        String companyId = UserIdThread.get().getCompanyId();
        switch (choose){
            case 1:
                costAssignmentMapper.deletePcCutPriceDetail(request.getStyleNo(),request.getStyleColor(),companyId);
                break;
            case 2:
                costAssignmentMapper.deletePcCutPriceDetail0(request.getStyleNo(),request.getStyleColor(),companyId);
                break;
            default:
                return ResponseInfo.error("参数错误!");
        }
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 冲裁型体单价明细修改
     * @param request
     * @return
     */
    @Override
    public ResponseInfo updatePcCutPriceDetail(UpdatePcCutPriceDetailRequest request) {
        if (ObjectUtils.isEmpty(request.getStyleNoDetail().getStyleNo())||ObjectUtils.isEmpty(request.getStyleNoDetail().getStyleColor())){
            return ResponseInfo.error("型体/颜色不能为空!");
        }
        if (!ObjectUtils.isEmpty(request.getStyleNoDetail().getCfmFlag())&& Objects.equals(request.getStyleNoDetail().getCfmFlag(),DefineEnum.CHECKOUT_FLAG.getValue())){
            return ResponseInfo.error("该冲裁型体单价明细已经检核,不能修改!");
        }
        if (!ObjectUtils.isEmpty(request.getList())){
            List<PcCutPriceDetail> list = request.getList().stream().map(t -> {
                PcCutPriceDetail pcCutPriceDetail = new PcCutPriceDetail();
                BeanUtil.copyProperties(t, pcCutPriceDetail);
                String userName = UserInfoUtil.getUserInfo().getUserName();
                pcCutPriceDetail.setStyle(request.getStyleNoDetail().getStyleNo());
                pcCutPriceDetail.setStyleColor(request.getStyleNoDetail().getStyleColor());
                pcCutPriceDetail.setSysDate(LocalDateTime.now());
                pcCutPriceDetail.setSysUser(userName);
                pcCutPriceDetail.setCompanyId(UserIdThread.get().getCompanyId());
                return pcCutPriceDetail;
            }).collect(Collectors.toList());
            costAssignmentMapper.updatePcCutPriceDetail(list);
        }
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 检核/取消检核
     * @param request
     * @param choose
     * @return
     */
    @Override
    public ResponseInfo CheckOutPcCutPriceDetail(StyleNoToColorRequest request, Integer choose) {
        if (ObjectUtils.isEmpty(request.getStyleNo())||ObjectUtils.isEmpty(request.getStyleColor())){
            return ResponseInfo.error("型体/颜色不能为空!");
        }
        String flag = request.getCfmFlag();
        String companyId = UserIdThread.get().getCompanyId();
        switch (choose){
            case 0:
                if (!StringUtils.isEmpty(flag)&&flag.equals(DefineEnum.CHECKOUT_FLAG.getValue())){
                    return ResponseInfo.error("该型体冲裁明细已经检核,不能再次检核!");
                }
                List<PcCutPriceDetailDto> dtoList = costAssignmentMapper.getUnitPriceOfPunchingType(request.getStyleNo(), request.getStyleColor(), companyId);
                int cutPrice=0;
                int pieceNum=0;
                int cutLayer=0;
                for (PcCutPriceDetailDto t : dtoList) {
                    if (ObjectUtils.isEmpty(t.getCutPrice())){
                        cutPrice++;
                    }
                    if (ObjectUtils.isEmpty(t.getPieceNum())){
                        pieceNum++;
                    }
                    if (ObjectUtils.isEmpty(t.getCutLayer())){
                        cutLayer++;
                    }
                }
                if (cutPrice>0){
                    return ResponseInfo.error("有"+cutPrice+"个冲裁单价为空的记录,不能检核!");
                }
                if (pieceNum>0){
                    return ResponseInfo.error("有"+pieceNum+"个片数为空的记录,不能检核!");
                }
                if (cutLayer>0){
                    return ResponseInfo.error("有"+cutLayer+"个层数为空的记录,不能检核!");
                }
                costAssignmentMapper.updatePcCutPriceDetailToCheck(request.getStyleNo(),request.getStyleColor(),DefineEnum.CHECKOUT_FLAG.getValue(),LocalDateTime.now(),UserInfoUtil.getUserInfo().getUserName(),companyId);
                break;
            case 1:
                if (StringUtils.isEmpty(flag)){
                    return ResponseInfo.error("该型体冲裁明细未检核,不能取消检核!");
                }
                costAssignmentMapper.updatePcCutPriceDetailToCheck(request.getStyleNo(),request.getStyleColor(),null,null,null,companyId);
                break;
            default:
                return ResponseInfo.error("参数错误!");
        }
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 复制价格到其他型体
     * @param map@return
     */
    @Override
    public ResponseInfo copyPriceToOtherStyle(Map<String, String> map) {
        String styleNo = map.get("styleNo");
        String styleColor = map.get("styleColor");
        String overRide = map.get("overRide");
        if (ObjectUtils.isEmpty(styleNo)||ObjectUtils.isEmpty(styleColor)){
            return ResponseInfo.error("型体/颜色不能为空!");
        }
        String companyId = UserIdThread.get().getCompanyId();
        List<PcCutPriceDetailDto> list = costAssignmentMapper.getUnitPriceOfPunchingType(styleNo,styleColor, companyId);
        if (ObjectUtils.isEmpty(list)){
            return ResponseInfo.error("该型体冲裁明细为空!");
        }
        List<PcCutPriceDetailDto> prices = list.stream().filter(t -> t.getCutPrice() != null).collect(Collectors.toList());
        if (ObjectUtils.isEmpty(prices)){
            return ResponseInfo.error("该型体冲裁明细无单价,不能复制!");
        }
        List<PcCutPriceDetail> detailList = costAssignmentMapper.getUnitPriceOfPunchingType2(styleNo, styleColor,companyId);
        if (ObjectUtils.isEmpty(detailList)){
            return ResponseInfo.error("该型体暂无其他颜色资料,不能复制!");
        }
        List<PcCutPriceDetail> prices2 = detailList.stream().filter(t -> t.getCutPrice() != null).collect(Collectors.toList());
        if (!ObjectUtils.isEmpty(prices2)&&"0".equals(overRide)){
            return ResponseInfo.warn("该型体其他颜色有单价,是否覆盖?");
        }
        String userName = UserInfoUtil.getUserInfo().getUserName();
        for (PcCutPriceDetail detail : detailList) {
            for (PcCutPriceDetailDto dto : list) {
                if (detail.getPartName().equals(dto.getPartName())) {
                    if (dto.getCutPrice()!=null){
                        detail.setCutPrice(dto.getCutPrice());
                    }
                    if (dto.getPieceNum()!=null){
                        detail.setPieceNum(dto.getPieceNum());
                    }
                    if (dto.getCutLayer()!=null){
                        detail.setCutLayer(dto.getCutLayer());
                    }
                    if (!ObjectUtils.isEmpty(dto.getRemark())){
                        detail.setRemark(dto.getRemark());
                    }
                    break;
                }
            }
            detail.setSysUser(userName);
            detail.setSysDate(LocalDateTime.now());
        }
        costAssignmentMapper.updatePcCutPriceDetail(detailList);
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 从其他型体复制单价
     * @param map
     * @return
     */
    @Override
    public ResponseInfo copyPriceToOtherStyle2(Map<String, String> map) {
        String styleNo = map.get("styleNo");
        String newStyleNo = map.get("newStyleNo");
        String styleColor = map.get("styleColor");
        String newStyleColor = map.get("newStyleColor");
        String overRide = map.get("overRide");
        if (ObjectUtils.isEmpty(styleNo)||ObjectUtils.isEmpty(styleColor)){
            return ResponseInfo.error("原型体/颜色不能为空!");
        }
        if (ObjectUtils.isEmpty(newStyleNo)||ObjectUtils.isEmpty(newStyleColor)){
            return ResponseInfo.error("目标型体/颜色不能为空!");
        }
        if (styleNo.equals(newStyleNo)&&styleColor.equals(newStyleColor)){
            return ResponseInfo.error("原型体/颜色不能与目标型体/颜色相同!");
        }
        String companyId = UserIdThread.get().getCompanyId();
        List<PcCutPriceDetailDto> list = costAssignmentMapper.getUnitPriceOfPunchingType(styleNo,styleColor, companyId);
        if (ObjectUtils.isEmpty(list)){
            return ResponseInfo.error("源型体冲裁明细为空!");
        }
        List<PcCutPriceDetailDto> prices = list.stream().filter(t -> t.getCutPrice() != null).collect(Collectors.toList());
        if (ObjectUtils.isEmpty(prices)) {
            return ResponseInfo.error("源型体冲裁明细无单价,不能复制!");
        }
        List<PcCutPriceDetailDto> list2 = costAssignmentMapper.getUnitPriceOfPunchingType(newStyleNo,newStyleColor, companyId);
        if (ObjectUtils.isEmpty(list2)){
            return ResponseInfo.error("目标型体冲裁明细为空!");
        }
        List<PcCutPriceDetailDto> prices2 = list2.stream().filter(t -> t.getCutPrice() != null).collect(Collectors.toList());
        if (!ObjectUtils.isEmpty(prices2)&&"0".equals(overRide)){
            return ResponseInfo.warn("目标型体颜色有单价,是否覆盖?");
        }
        String userName = UserInfoUtil.getUserInfo().getUserName();
        List<PcCutPriceDetail> details = new ArrayList<>();
        for (PcCutPriceDetailDto t2 : list2) {
            PcCutPriceDetail detail = new PcCutPriceDetail();
            BeanUtil.copyProperties(t2,detail);
            for (PcCutPriceDetailDto t : list) {
                if (t2.getPartName().equals(t.getPartName())){
                    if (t.getCutPrice()!=null){
                        detail.setCutPrice(t.getCutPrice());
                    }
                    if (t.getPieceNum()!=null){
                        detail.setPieceNum(t.getPieceNum());
                    }
                    if (t.getCutLayer()!=null){
                        detail.setCutLayer(t.getCutLayer());
                    }
                    if (!ObjectUtils.isEmpty(t.getRemark())){
                        detail.setRemark(t.getRemark());
                    }
                    break;
                }
            }
            detail.setCompanyId(companyId);
            detail.setStyle(newStyleNo);
            detail.setStyleColor(newStyleColor);
            detail.setSysUser(userName);
            detail.setSysDate(LocalDateTime.now());
            details.add(detail);
        }
        costAssignmentMapper.updatePcCutPriceDetail(details);
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 选择指令
     * @param request
     * @param choose
     * @return
     */
    @Override
    public ResponseInfo LotNoDetail(LotNoCutPriceRequest request, Integer choose) {
        if (request.getPageNum() == null || request.getPageSize() == null) {
            request.setPageNum(1);
            request.setPageSize(10);
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        request.setCompanyId(UserIdThread.get().getCompanyId());
        PageRecord<LotNoDetailDto> list = new PageRecord<>();
        List<LotNoDetailDto> dtoList;
        switch (choose){
            case 1:
                dtoList = costAssignmentMapper.getLotNoDetail(request);
                break;
            case 2:
                dtoList = costAssignmentMapper.getLotNoDetail2(request);
                break;
            default:
                return ResponseInfo.error("参数错误!");
        }
        list.setList(dtoList);
        PageInfo pageInfo = new PageInfo(dtoList);
        list.setTotal(pageInfo.getTotal());
        return ResponseInfo.ok(list);
    }

    /**
     * 指令查询
     * @param request
     * @param choose
     * @return
     */
    @Override
    public ResponseInfo getLotNoDetail(LotNoCutPriceRequest request, Integer choose) {
        if (request.getPageNum() == null || request.getPageSize() == null) {
            request.setPageNum(1);
            request.setPageSize(10);
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        request.setCompanyId(UserIdThread.get().getCompanyId());
        PageRecord<LotNoDetailDto> list = new PageRecord<>();
        List<LotNoDetailDto> dtoList;
        switch (choose){
            case 1:
                dtoList = costAssignmentMapper.getLotNoDetailList(request);
                break;
            case 2:
                dtoList = costAssignmentMapper.getLotNoDetailList2(request);
                break;
            default:
                return ResponseInfo.error("参数错误!");
        }
        for (LotNoDetailDto t : dtoList) {
            if (ObjectUtils.isEmpty(t.getCfmFlag())){
                t.setCfmFlag(DefineEnum.CHECKOUT_FLAG_N.getValue());
            }
        }
        list.setList(dtoList);
        PageInfo pageInfo = new PageInfo(dtoList);
        list.setTotal(pageInfo.getTotal());
        return ResponseInfo.ok(list);
    }

    /**
     * 指令冲裁单价明细
     * @param request
     * @return
     */
    @Override
    public ResponseInfo LotNoUnitPriceOfPunchingType(LotNoRequest request) {
        if (ObjectUtils.isEmpty(request.getLotNo())){
            return ResponseInfo.error("指令不能为空!");
        }
        HashMap map=new HashMap();
        String companyId = UserIdThread.get().getCompanyId();
        List<PcCutPriceDetailDto> list = costAssignmentMapper.getPcCutLotPriceDetail(request.getLotNo(),companyId);
        //冲裁单价总数
        BigDecimal countCutPrice = BigDecimal.ZERO;
        if (!ObjectUtils.isEmpty(list)){
            for (PcCutPriceDetailDto t : list) {
                if (!ObjectUtils.isEmpty(t.getCutPrice())) {
                    countCutPrice=countCutPrice.add(t.getCutPrice());
                }
            }
        }
        map.put("list",list);
        map.put("totalCutPrice",countCutPrice);
        return ResponseInfo.ok(map);
    }

    /**
     * 生成指令单价
     * @param request
     * @return
     */
    @Override
    public ResponseInfo GenerateInstructionUnitPrice(generateCutLotNoPriceRequest request) {
        if (ObjectUtils.isEmpty(request.getLotNo())&&ObjectUtils.isEmpty(request.getStyle())&&ObjectUtils.isEmpty(request.getColor())){
            return ResponseInfo.error("指令/型体/颜色不能为空!");
        }
        if (ObjectUtils.isEmpty(request.getCfmFlag())){
            return ResponseInfo.error("存在型体单价未建档的指令记录,不能处理!");
        }
        UserInfoUtil.UserInfo userInfo = UserInfoUtil.getUserInfo();
        List<PcCutPriceDetailDto> cutPriceDetailList = costAssignmentMapper.getUnitPriceOfPunchingType(request.getStyle(), request.getColor(), userInfo.getCompanyId());
        if (!ObjectUtils.isEmpty(cutPriceDetailList)){
            List<PcCutLotPriceDetail> list = cutPriceDetailList.stream().map(t -> {
                PcCutLotPriceDetail pcCutLotPriceDetail = new PcCutLotPriceDetail();
                BeanUtil.copyProperties(t, pcCutLotPriceDetail);
                pcCutLotPriceDetail.setCompanyId(userInfo.getCompanyId());
                pcCutLotPriceDetail.setSysUser(userInfo.getUserName());
                pcCutLotPriceDetail.setSysDate(LocalDateTime.now());
                pcCutLotPriceDetail.setLotNo(request.getLotNo());
                pcCutLotPriceDetail.setStyle(request.getStyle());
                pcCutLotPriceDetail.setStyleColor(request.getColor());
                return pcCutLotPriceDetail;
            }).collect(Collectors.toList());
            costAssignmentMapper.addPcCutLotPriceDetail(list);
        }
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 重新生成指令单价
     * @param request
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo RegenerateInstructionUnitPrice(generateCutLotNoPriceRequest request) {
        if (ObjectUtils.isEmpty(request.getLotNo())&&ObjectUtils.isEmpty(request.getStyle())&&ObjectUtils.isEmpty(request.getColor())){
            return ResponseInfo.error("指令/型体/颜色不能为空!");
        }
        if (!ObjectUtils.isEmpty(request.getCfmFlag())&&request.getCfmFlag().equals(DefineEnum.CHECKOUT_FLAG.getValue())){
            return ResponseInfo.error("财务已经检核,不能处理!");
        }
        UserInfoUtil.UserInfo userInfo = UserInfoUtil.getUserInfo();
        List<PcCutPriceDetailDto> cutPriceDetailList = costAssignmentMapper.getUnitPriceOfPunchingType(request.getStyle(), request.getColor(), userInfo.getCompanyId());
        if (!ObjectUtils.isEmpty(cutPriceDetailList)){
            List<PcCutLotPriceDetail> list = cutPriceDetailList.stream().map(t -> {
                PcCutLotPriceDetail pcCutLotPriceDetail = new PcCutLotPriceDetail();
                BeanUtil.copyProperties(t, pcCutLotPriceDetail);
                pcCutLotPriceDetail.setCompanyId(userInfo.getCompanyId());
                pcCutLotPriceDetail.setSysUser(userInfo.getUserName());
                pcCutLotPriceDetail.setSysDate(LocalDateTime.now());
                pcCutLotPriceDetail.setLotNo(request.getLotNo());
                pcCutLotPriceDetail.setStyle(request.getStyle());
                pcCutLotPriceDetail.setStyleColor(request.getColor());
                return pcCutLotPriceDetail;
            }).collect(Collectors.toList());
            costAssignmentMapper.deletePcCutLotPriceDetail(request.getLotNo(),userInfo.getCompanyId());
            costAssignmentMapper.addPcCutLotPriceDetail(list);
        }
        return ResponseInfo.ok("操作成功!");
    }

    @Resource
    private PcLotHeadMapper pcLotHeadMapper;

    /**
     * 冲裁单价导出
     * @param lotNo
     * @param response
     */
    @Override
    public void ExportOfPunchingInstructions(String lotNo, HttpServletResponse response) {
        String fileName = "裁断单价明细表_" + DateUtils.dateTimeNow() + ".xlsx";
        String companyId = UserIdThread.get().getCompanyId();
        PunchingExportVo vo = pcLotHeadMapper.getPcLotHead(lotNo,companyId);
        if (ObjectUtils.isEmpty(vo)){
            throw new ServiceErrorException("指令不存在");
        }
        HashMap<String, Object> map = new HashMap<>();
        List<PcCutPriceDetailDto> list = costAssignmentMapper.getPcCutLotPriceDetail(lotNo, companyId);
        BigDecimal count = BigDecimal.ZERO;
        for (PcCutPriceDetailDto t : list) {
            if (!ObjectUtils.isEmpty(t.getCutPrice())) {
                count = count.add(t.getCutPrice());
            }
        }
        vo.setDate(DateUtils.getDate());
        map.put("mapList", list);
        map.put("t", vo);
        map.put("count", count);
        TemplateExportParams templateParams = new TemplateExportParams("templates/冲裁指令单价明细模板.xls", true);
        try {
            byte[] imageBytes = ImageUtils.readAndResizeImage(vo.getPhotoPath(), 150, 250);
            ExcelUtils.setResponseZF(response, fileName);
            ExcelPoiUtils.writeExcelWithPictureToResponse(response, templateParams, map, imageBytes, 5, 5, 1, 2);
        } catch (Exception e) {
            log.error("裁断单价明细表导出失败, 错误信息: {}", e.getMessage());
        }
    }

    /**
     * 工艺工序查询
     * @param request
     * @return
     */
    @Override
    public ResponseInfo ProcessStepsList(StyleNoToColorRequest request) {
        if (ObjectUtils.isEmpty(request.getStyleNo())||ObjectUtils.isEmpty(request.getStyleColor())){
            return ResponseInfo.error("型体或颜色不能为空!");
        }
        Map map=new HashMap();
        String companyId = UserIdThread.get().getCompanyId();
        List<PcCutPriceDetailODto> list = costAssignmentMapper.getPcCutPriceDetailO(request.getStyleNo(), request.getStyleColor(), companyId);
        BigDecimal count=BigDecimal.ZERO;
        if (!ObjectUtils.isEmpty(list)){
            for (PcCutPriceDetailODto t : list) {
                if (!ObjectUtils.isEmpty(t.getPrice())){
                    count=count.add(t.getPrice());
                }
            }
        }
        map.put("list",list);
        map.put("count",count);
        return ResponseInfo.ok(map);
    }

    /**
     * 0检核/1取消检核
     * @param request
     * @param choose
     * @return
     */
    @Override
    public ResponseInfo CheckOutPcCutPriceDetailO(StyleNoToColorRequest request, Integer choose) {
        if (ObjectUtils.isEmpty(request.getStyleNo())||ObjectUtils.isEmpty(request.getStyleColor())){
            return ResponseInfo.error("型体/颜色不能为空!");
        }
        String flag = request.getCfmFlag();
        String companyId = UserIdThread.get().getCompanyId();
        switch (choose){
            case 0:
                if (!StringUtils.isEmpty(flag)&&flag.equals(DefineEnum.CHECKOUT_FLAG.getValue())){
                    return ResponseInfo.error("该型体工艺工序已经检核,不能再次检核!");
                }
                List<PcCutPriceDetailODto> list = costAssignmentMapper.getPcCutPriceDetailO(request.getStyleNo(), request.getStyleColor(), companyId);
                int priceCount=0;
                for (PcCutPriceDetailODto t : list) {
                    if (ObjectUtils.isEmpty(t.getPrice())){
                        priceCount++;
                    }
                }
                if (priceCount>0){
                    return ResponseInfo.error("有"+priceCount+"个单价为空的记录,不能检核!");
                }
                costAssignmentMapper.updatePcCutPriceDetail0ToCheck(request.getStyleNo(),request.getStyleColor(),DefineEnum.CHECKOUT_FLAG.getValue(),LocalDateTime.now(),UserInfoUtil.getUserInfo().getUserName());
                break;
            case 1:
                if (StringUtils.isEmpty(flag)){
                    return ResponseInfo.error("该型体工艺工序未检核,不能取消检核!");
                }
                costAssignmentMapper.updatePcCutPriceDetail0ToCheck(request.getStyleNo(),request.getStyleColor(),null,null,null);
                break;
            default:
                return ResponseInfo.error("参数错误!");
        }
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 工艺导出
     * @param request
     * @param response
     */
    @Override
    public void ExportOfProcessSteps(StyleNoToColorRequest request, HttpServletResponse response) {
        String fileName = "手工单价明细表_" + DateUtils.dateTimeNow() + ".xlsx";
        String companyId = UserIdThread.get().getCompanyId();
        PunchingExportVo vo = costAssignmentMapper.getStyleDetail(request.getStyleNo(),companyId);
        if (!ObjectUtils.isEmpty(vo)){
            BigDecimal count=BigDecimal.ZERO;
            List<PcCutPriceDetailODto> list = costAssignmentMapper.getPcCutPriceDetailO(request.getStyleNo(), request.getStyleColor(), companyId);
            for (PcCutPriceDetailODto t : list) {
                if (t.getPrice()!=null){
                    count=count.add(t.getPrice());
                }
            }
            vo.setStyle(request.getStyleNo());
            vo.setColor(request.getStyleColor());
            vo.setDate(DateUtils.getDate());
            vo.setCount(count);
            try (
                    InputStream inputStream = new ClassPathResource("templates/手工单价明细表模板.xls").getInputStream();
                    OutputStream outputStream = response.getOutputStream();
                    ExcelWriter excelWriter = EasyExcel.write(outputStream).excelType(ExcelTypeEnum.XLS).withTemplate(inputStream).build();
            ) {
                ExcelUtils.setResponseZF(response, fileName);
                WriteSheet writeSheet = EasyExcel.writerSheet().build();
                FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
                excelWriter.fill(vo, writeSheet);
                excelWriter.fill(new FillWrapper("t", list), fillConfig, writeSheet);
                excelWriter.finish();
            }
            catch (NullPointerException e){
                log.error("模板文件不存在, 错误信息: {}", e.getMessage());
            }catch (Exception e) {
                log.error("手工单价明细表导出失败, 错误信息: {}", e.getMessage());
            }
        }
    }

    /**
     * 1 生成指令单价 2重新生成指令单价
     * @param request
     * @param choose
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo GenerateInstructionProcessUnitPrice(generateCutLotNoPriceRequest request, Integer choose) {
        if (StringUtils.isAnyBlank(request.getLotNo(), request.getStyle(), request.getColor())) {
            return ResponseInfo.error("指令/型体/颜色不能为空!");
        }
        switch (choose) {
            case 1:
                if (StringUtils.isBlank(request.getCfmFlag())) {
                    return ResponseInfo.error("存在型体单价未建档的指令记录,不能处理!");
                }
                addPcCutLotPriceDetailO(request);
                break;
            case 2:
                if (!StringUtils.isEmpty(request.getCfmFlag())&&DefineEnum.CHECKOUT_FLAG.getValue().equals(request.getCfmFlag())) {
                    return ResponseInfo.error("财务已经检核,不能处理!");
                }
                 addPcCutLotPriceDetailO(request);
                break;
            default:
                return ResponseInfo.error("参数错误!");
        }
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 手工指令新增操作
     * @param request
     * @return
     */
    private void addPcCutLotPriceDetailO(generateCutLotNoPriceRequest request) {
        try {
            UserInfoUtil.UserInfo userInfo = UserInfoUtil.getUserInfo();
            List<PcCutPriceDetailODto> list = costAssignmentMapper.getPcCutPriceDetailO(request.getStyle(), request.getColor(), userInfo.getCompanyId());
            List<PcCutLotPriceDetailO> pcCutLotPriceDetailOList = list.stream().map(dto -> {
                PcCutLotPriceDetailO entity = new PcCutLotPriceDetailO();
                BeanUtil.copyProperties(dto, entity);
                entity.setCompanyId(userInfo.getCompanyId());
                entity.setSysUser(userInfo.getUserName());
                entity.setSysDate(LocalDateTime.now());
                entity.setLotNo(request.getLotNo());
                entity.setStyle(request.getStyle());
                entity.setStyleColor(request.getColor());
                entity.setProcessCode("01");
                return entity;
            }).collect(Collectors.toList());
            if (!ObjectUtils.isEmpty(pcCutLotPriceDetailOList)){
                costAssignmentMapper.deletePcCutLotPriceDetail0(request.getLotNo(),userInfo.getCompanyId());
                costAssignmentMapper.addPcCutLotPriceDetailO(pcCutLotPriceDetailOList);
            }
        } catch (Exception e) {
            // 处理异常情况
            log.error("生成指令工艺单价失败: " + e.getMessage());
        }
    }

    /**
     * 手工指令单价导出
     * @param lotNo
     * @param response
     */
    @Override
    public void ExportManualInstructionUnitPrice(String lotNo, HttpServletResponse response) {
        String fileName =lotNo+ "手工单价明细表_" + DateUtils.dateTimeNow() + ".xlsx";
        String companyId = UserIdThread.get().getCompanyId();
        PunchingExportVo vo = pcLotHeadMapper.getPcLotHead(lotNo, companyId);
        if (ObjectUtils.isEmpty(vo)){
            throw new ServiceErrorException("指令不存在!");
        }
        HashMap<String, Object> map = new HashMap<>();
        BigDecimal count = BigDecimal.ZERO;
        List<PcCutPriceDetailODto> list = costAssignmentMapper.getPcCutLotPriceDetailO(lotNo, companyId);
        for (PcCutPriceDetailODto t : list) {
            if (t.getPrice() != null) {
                count = count.add(t.getPrice());
            }
        }
        vo.setDate(DateUtils.getDate());
        map.put("mapList", list);
        map.put("t", vo);
        map.put("count", count);
        map.put("sheets",Arrays.asList(0));
        TemplateExportParams templateParams = new TemplateExportParams("templates/手工指令单价模板.xls", true);
        try {
            byte[] imageBytes = ImageUtils.readAndResizeImage(vo.getPhotoPath(),170,300);
            ExcelUtils.setResponseZF(response,fileName);
            ExcelPoiUtils.writeExcelWithPictureToResponse(response,templateParams,map,imageBytes,5,6,1,3);
        } catch (Exception e) {
            log.error("手工指令单价表导出失败, 错误信息: {}", e.getMessage());
        }
    }

    /**
     * 手工指令工艺单价明细
     * @param request
     * @return
     */
    @Override
    public ResponseInfo InstructionProcessUnitPriceDetails(LotNoRequest request) {
        if (ObjectUtils.isEmpty(request.getLotNo())){
            return ResponseInfo.error("指令不能为空!");
        }
        HashMap map=new HashMap();
        String companyId = UserIdThread.get().getCompanyId();
        List<PcCutPriceDetailODto> list = costAssignmentMapper.getPcCutLotPriceDetailO(request.getLotNo(),companyId);
        //指令工艺单价总数
        BigDecimal countCutPrice = BigDecimal.ZERO;
        if (!ObjectUtils.isEmpty(list)){
            for (PcCutPriceDetailODto t : list) {
                if (!ObjectUtils.isEmpty(t.getPrice())) {
                    countCutPrice=countCutPrice.add(t.getPrice());
                }
            }
        }
        map.put("list",list);
        map.put("totalCutPrice",countCutPrice);
        return ResponseInfo.ok(map);
    }

    /**
     * 工艺工序修改
     * @param request
     * @return
     */
    @Override
    public ResponseInfo updatePcCutPriceDetail0(UpdatePcCutPriceDetail0Request request) {
        if (ObjectUtils.isEmpty(request.getStyleNoDetail().getStyleNo())||ObjectUtils.isEmpty(request.getStyleNoDetail().getStyleColor())){
            return ResponseInfo.error("型体/颜色不能为空!");
        }
        if (!ObjectUtils.isEmpty(request.getStyleNoDetail().getCfmFlag())&& Objects.equals(request.getStyleNoDetail().getCfmFlag(),DefineEnum.CHECKOUT_FLAG.getValue())){
            return ResponseInfo.error("该手工型体单价明细已经检核,不能修改!");
        }
        if (!ObjectUtils.isEmpty(request.getList())){
            List<PcCutLotPriceDetailO> list = request.getList().stream().map(t -> {
                PcCutLotPriceDetailO pcCutLotPriceDetailO = new PcCutLotPriceDetailO();
                BeanUtil.copyProperties(t, pcCutLotPriceDetailO);
                String userName = UserInfoUtil.getUserInfo().getUserName();
                pcCutLotPriceDetailO.setStyle(request.getStyleNoDetail().getStyleNo());
                pcCutLotPriceDetailO.setStyleColor(request.getStyleNoDetail().getStyleColor());
                pcCutLotPriceDetailO.setSysDate(LocalDateTime.now());
                pcCutLotPriceDetailO.setSysUser(userName);
                pcCutLotPriceDetailO.setCompanyId(UserIdThread.get().getCompanyId());
                return pcCutLotPriceDetailO;
            }).collect(Collectors.toList());
            costAssignmentMapper.updatePcCutPriceDetail0(list);
        }
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 复制单价到其他型体颜色
     * @param map
     * @return
     */
    @Override
    public ResponseInfo copyPriceToOtherStyle3(Map<String, String> map) {
        String styleNo = map.get("styleNo");
        String styleColor = map.get("styleColor");
        String overRide = map.get("overRide");
        if (ObjectUtils.isEmpty(styleNo)||ObjectUtils.isEmpty(styleColor)){
            return ResponseInfo.error("型体/颜色不能为空!");
        }
        String companyId = UserIdThread.get().getCompanyId();
        List<PcCutPriceDetailODto> list = costAssignmentMapper.getPcCutPriceDetailO(styleNo,styleColor,companyId);
        if (ObjectUtils.isEmpty(list)){
            return ResponseInfo.error("该型体手工明细为空!");
        }
        List<PcCutPriceDetailODto> prices = list.stream().filter(t -> t.getPrice() != null).collect(Collectors.toList());
        if (ObjectUtils.isEmpty(prices)){
            return ResponseInfo.error("该型体手工明细无单价,不能复制!");
        }
        List<PcCutLotPriceDetailO> detailList = costAssignmentMapper.getPcCutPriceDetailO2(styleNo, styleColor,companyId);
        if (ObjectUtils.isEmpty(detailList)){
            return ResponseInfo.error("该型体暂无其他颜色资料,不能复制!");
        }
        List<PcCutLotPriceDetailO> prices2 = detailList.stream().filter(t -> t.getPrice() != null).collect(Collectors.toList());
        if (!ObjectUtils.isEmpty(prices2)&&"0".equals(overRide)){
            return ResponseInfo.warn("该型体其他颜色有单价,是否覆盖?");
        }
        String userName = UserInfoUtil.getUserInfo().getUserName();
        for (PcCutLotPriceDetailO detail : detailList) {
            for (PcCutPriceDetailODto dto : list) {
                if (detail.getPartName().equals(dto.getPartName())&&detail.getProcess().equals(dto.getProcess())) {
                    if (dto.getPrice()!= null){
                        detail.setPrice(dto.getPrice());
                    }
                    if (dto.getPieceNum()!= null){
                        detail.setPieceNum(dto.getPieceNum());
                    }
                    if (!ObjectUtils.isEmpty(dto.getRemark())){
                        detail.setRemark(dto.getRemark());
                    }
                    break;
                }
            }
            detail.setSysUser(userName);
            detail.setSysDate(LocalDateTime.now());
        }
        costAssignmentMapper.updatePcCutPriceDetail0(detailList);
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 从其他型体复制单价
     * @param map
     * @return
     */
    @Override
    public ResponseInfo copyPriceToOtherStyle4(Map<String, String> map) {
        String styleNo = map.get("styleNo");
        String newStyleNo = map.get("newStyleNo");
        String styleColor = map.get("styleColor");
        String newStyleColor = map.get("newStyleColor");
        String overRide = map.get("overRide");
        if (ObjectUtils.isEmpty(styleNo)||ObjectUtils.isEmpty(styleColor)){
            return ResponseInfo.error("原型体/颜色不能为空!");
        }
        if (ObjectUtils.isEmpty(newStyleNo)||ObjectUtils.isEmpty(newStyleColor)){
            return ResponseInfo.error("目标型体/颜色不能为空!");
        }
        if (styleNo.equals(newStyleNo)&&styleColor.equals(newStyleColor)){
            return ResponseInfo.error("原型体/颜色不能与目标型体/颜色相同!");
        }
        String companyId = UserIdThread.get().getCompanyId();
        List<PcCutPriceDetailODto> list = costAssignmentMapper.getPcCutPriceDetailO(styleNo,styleColor, companyId);
        if (ObjectUtils.isEmpty(list)){
            return ResponseInfo.error("源型体手工明细为空!");
        }
        List<PcCutPriceDetailODto> prices = list.stream().filter(t -> t.getPrice() != null).collect(Collectors.toList());
        if (ObjectUtils.isEmpty(prices)){
            return ResponseInfo.error("源型体手工明细无单价,不能复制!");
        }
        List<PcCutPriceDetailODto> list2 = costAssignmentMapper.getPcCutPriceDetailO(newStyleNo,newStyleColor, companyId);
        if (ObjectUtils.isEmpty(list2)){
            return ResponseInfo.error("目标型体手工明细为空!");
        }
        List<PcCutPriceDetailODto> prices2 = list2.stream().filter(t -> t.getPrice() != null).collect(Collectors.toList());
        if (!ObjectUtils.isEmpty(prices2)&&"0".equals(overRide)){
            return ResponseInfo.warn("目标型体颜色有单价,是否覆盖?");
        }
        String userName = UserInfoUtil.getUserInfo().getUserName();
        List<PcCutLotPriceDetailO> details = new ArrayList<>();
        for (PcCutPriceDetailODto t : list) {
            for (PcCutPriceDetailODto t2 : list2) {
                if (t2.getProcess().equals(t.getProcess())&&t2.getPartName().equals(t.getPartName())){
                    PcCutLotPriceDetailO detail = new PcCutLotPriceDetailO();
                    BeanUtil.copyProperties(t2,detail);
                    if (t.getPrice()!= null){
                        detail.setPrice(t.getPrice());
                    }
                    if (t.getPieceNum()!= null){
                        detail.setPieceNum(t.getPieceNum());
                    }
                    if (!ObjectUtils.isEmpty(t.getRemark())){
                        detail.setRemark(t.getRemark());
                    }
                    detail.setStyle(newStyleNo);
                    detail.setStyleColor(newStyleColor);
                    detail.setSysUser(userName);
                    detail.setSysDate(LocalDateTime.now());
                    details.add(detail);
                }
            }
        }
        costAssignmentMapper.updatePcCutPriceDetail0(details);
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 冲裁单价导出
     * @param request
     * @param response
     */
    @Override
    public void ExportOfPunchingUnitPrice(StyleNoToColorRequest request, HttpServletResponse response) {
        String fileName = "冲裁单价明细表_" + DateUtils.dateTimeNow() + ".xls";
        String companyId = UserIdThread.get().getCompanyId();
        PunchingExportVo vo = costAssignmentMapper.getStyleDetail(request.getStyleNo(), companyId);
        HashMap<String, Object> map = new HashMap<>();
        List<PcCutPriceDetailDto> list = costAssignmentMapper.getUnitPriceOfPunchingType(request.getStyleNo(), request.getStyleColor(), companyId);
        BigDecimal count = BigDecimal.ZERO;
        for (PcCutPriceDetailDto t : list) {
            if (!ObjectUtils.isEmpty(t.getCutPrice())) {
                count = count.add(t.getCutPrice());
            }
        }
        vo.setDate(DateUtils.getDate());
        vo.setStyle(request.getStyleNo());
        vo.setColor(request.getStyleColor());
        map.put("mapList", list);
        map.put("t", vo);
        map.put("count", count);
        TemplateExportParams templateParams = new TemplateExportParams("templates/冲裁单价明细表模板.xls", true);
        try {
            ExcelUtils.setResponseZF(response, fileName);
            Workbook workbook = ExcelExportUtil.exportExcel(templateParams, map);
            workbook.write(response.getOutputStream());
            workbook.close();
        } catch (Exception e) {
            log.error("冲裁单价明细表导出失败, 错误信息: {}", e.getMessage());
        }
    }

    @Resource
    private PcOutListPriceMapper pcOutListPriceMapper;

    /**
     * 手工单价取数
     * @param request
     * @return
     */
    @Override
    public ResponseInfo ManualUnitPriceRetrieval(StyleNoToColorRequest request) {
        if (ObjectUtils.isEmpty(request.getStyleNo())||ObjectUtils.isEmpty(request.getStyleColor())){
            return ResponseInfo.error("请选择型体/颜色!");
        }
        String companyId = UserIdThread.get().getCompanyId();
        Integer detailExist = costAssignmentMapper.getPcCutPriceDetail0Exist(request.getStyleNo(), request.getStyleColor(),companyId);
        if (detailExist!=null&&detailExist>0){
            return ResponseInfo.error("该型体手工明细已存在!");
        }
        String flag = pcOutListPriceMapper.getSdStyleProcessHead(request.getStyleNo(), request.getStyleColor(),companyId);
        if (!"Y".equals(flag)) {
            return ResponseInfo.error("该型体工艺未检核!");
        }
        List<SdStyleProcessNewDto> newList = pcOutListPriceMapper.getSdStyleProcessNewList(request.getStyleNo(), request.getStyleColor(), companyId);
        if (!ObjectUtils.isEmpty(newList)){
            List<PcCutPriceDetailO> list = getPcCutPriceDetailOList(newList, request.getStyleNo(), request.getStyleColor());
            if (!ObjectUtils.isEmpty(list)){
                list=list.stream()
                        .sorted(Comparator.comparing(PcCutPriceDetailO::getProcess)).collect(Collectors.toList());
                int seqNo = 1;
                for (PcCutPriceDetailO item : list) {
                    item.setSeqNo(BigDecimal.valueOf(seqNo));
                    seqNo++;
                }
                costAssignmentMapper.addPcCutPriceDetailO(list);
            }
        }
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 获取手工工序
     * @return
     */
    private List<String> getProcessList(){
        List<String> processList = costAssignmentMapper.getProcessList();
        List<String> filteredList = processList.stream()
                .filter(t -> !t.contains("冲裁") && !t.contains("二次改刀")&& !t.contains("贴流水标")&& !t.contains("二次改刀2")&& !t.contains("切割"))
                .collect(Collectors.toList());
        return filteredList;
    }

    /**
     * 通过反射获取手工工艺数据
     * @param newList
     * @param style
     * @param color
     * @return
     */
    public List<PcCutPriceDetailO> getPcCutPriceDetailOList(List<SdStyleProcessNewDto> newList, String style, String color) {
        List<PcCutPriceDetailO> priceList = new ArrayList<>();
        // 获取处理过的集合
        List<String> processList = getProcessList();
        // 遍历新列表中的每个 SdStyleProcessNewDto 对象
        try {
            for (SdStyleProcessNewDto t : newList) {
                // 遍历每个对象的 process1 到 process10 属性
                for (int i = 1; i <= 10; i++) {
                    String process = "getProcess" + i;
                    String processValue = (String) t.getClass().getMethod(process).invoke(t);

                    // 如果 process 值不为空且在处理过的集合中存在，则添加到 priceList 中
                    if (!ObjectUtils.isEmpty(processValue) && processList.contains(processValue)) {
                        PcCutPriceDetailO list = getPcCutPriceDetailO(style, color);
                        list.setProcess(processValue);
                        list.setPartName(t.getPartName());
                        list.setPieceNum(t.getPieceNum());
                        priceList.add(list);
                    }
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return priceList;
    }


    /**
     *  拿到每一个对象的初始值
     * @param style 型体
     * @param color 颜色
     */
    public PcCutPriceDetailO getPcCutPriceDetailO(String style,String color){
        PcCutPriceDetailO list = new PcCutPriceDetailO();
        UserInfoUtil.UserInfo userInfo = UserInfoUtil.getUserInfo();
        list.setCompanyId(userInfo.getCompanyId());
        list.setSysUser(userInfo.getUserName());
        list.setSysDate(LocalDateTime.now());
        list.setStyle(style);
        list.setStyleColor(color);
        list.setProcessCode("01");
        list.setProcessType("手工");
        return list;
    }

    /**
     * 获取开发差异
     * @param request
     * @return
     */
    @Override
    public ResponseInfo TakeDevelopmentDifferences(StyleNoToColorRequest request) {
        if (ObjectUtils.isEmpty(request.getStyleNo())||ObjectUtils.isEmpty(request.getStyleColor())){
            return ResponseInfo.error("型体/颜色不能为空!");
        }
        UserInfoUtil.UserInfo u = UserInfoUtil.getUserInfo();
        String flag = pcOutListPriceMapper.getSdStyleProcessHead(request.getStyleNo(), request.getStyleColor(),u.getCompanyId());
        if (!"Y".equals(flag)) {
            return ResponseInfo.error("该型体工艺未检核!");
        }
        List<SdStyleProcessNewDto> new2List = costAssignmentMapper.getSdStyleProcessNewToBlankingList(request.getStyleNo(), request.getStyleColor(),u.getCompanyId());
        if (ObjectUtils.isEmpty(new2List)){
            return ResponseInfo.error("bom工艺资料为空!");
        }
        List<PcCutPriceDetailDto> detailDto = costAssignmentMapper.getUnitPriceOfPunchingType(request.getStyleNo(),request.getStyleColor(),u.getCompanyId());
        if (ObjectUtils.isEmpty(detailDto)){
            return ResponseInfo.error("冲裁型体单价明细为空!");
        }
        List<PcCutPriceDetail> list = new ArrayList<>();
        //判断是否存在开发差异
        for (SdStyleProcessNewDto dto : new2List) {
            boolean exists = false;
            for (PcCutPriceDetailDto t : detailDto) {
                if (dto.getPartName().equals(t.getPartName())) {
                    exists = true;
                    break;
                }
            }
            if (!exists) {
                PcCutPriceDetail pcCutPriceDetail = new PcCutPriceDetail();
                BeanUtil.copyProperties(dto, pcCutPriceDetail);
                pcCutPriceDetail.setCompanyId(u.getCompanyId());
                pcCutPriceDetail.setSysUser(u.getUserName());
                pcCutPriceDetail.setSysDate(LocalDateTime.now());
                BigDecimal cutNum = getCutNum(pcCutPriceDetail.getPieceNum(), pcCutPriceDetail.getCutLayer());
                pcCutPriceDetail.setCutNum(cutNum);
                list.add(pcCutPriceDetail);
            }
        }
        if (!ObjectUtils.isEmpty(list)){
            BigDecimal maxSeqNo = BigDecimal.ZERO;
            for (PcCutPriceDetailDto t : detailDto) {
                if (t.getSeqNo().compareTo(maxSeqNo) > 0) {
                    maxSeqNo = t.getSeqNo();
                }
            }
            for (int i = 0; i < list.size(); i++) {
                list.get(i).setSeqNo(maxSeqNo.add(BigDecimal.valueOf(i + 1)));
            }
            costAssignmentMapper.addPcCutPriceDetail(list);
        }else {
            return ResponseInfo.warn("无差异!");
        }
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 取开发差异
     * @param request
     * @return
     */
    @Override
    public ResponseInfo TakeDevelopmentDifferences2(StyleNoToColorRequest request) {
        if (ObjectUtils.isEmpty(request.getStyleNo())||ObjectUtils.isEmpty(request.getStyleColor())){
            return ResponseInfo.error("型体/颜色不能为空!");
        }
        UserInfoUtil.UserInfo u = UserInfoUtil.getUserInfo();
        String flag = pcOutListPriceMapper.getSdStyleProcessHead(request.getStyleNo(), request.getStyleColor(),u.getCompanyId());
        if (!"Y".equals(flag)) {
            return ResponseInfo.error("该型体工艺未检核!");
        }
        List<PcCutPriceDetailODto> detailODtos = costAssignmentMapper.getPcCutPriceDetailO(request.getStyleNo(), request.getStyleColor(), u.getCompanyId());
        if (ObjectUtils.isEmpty(detailODtos)){
            return ResponseInfo.error("手工单价资料为空!");
        }
        List<SdStyleProcessNewDto> new2List = costAssignmentMapper.TakeDevelopmentDifferences2(request.getStyleNo(),request.getStyleColor(),u.getCompanyId());
        if (ObjectUtils.isEmpty(new2List)){
            return ResponseInfo.error("bom工艺资料为空!");
        }

        List<PcCutPriceDetailO> list = new ArrayList<>();
        for (SdStyleProcessNewDto dto : new2List) {
            boolean exists = false;
            for (PcCutPriceDetailODto t : detailODtos) {
                if (dto.getPartName().equals(t.getPartName())&&dto.getProcess().equals(t.getProcess())) {
                    exists = true;
                    break;
                }
            }
            if (!exists) {
                PcCutPriceDetailO pcCutPriceDetailO = getPcCutPriceDetailO(request.getStyleNo(),request.getStyleColor());
                pcCutPriceDetailO.setProcess(dto.getProcess());
                pcCutPriceDetailO.setPartName(dto.getPartName());
                pcCutPriceDetailO.setPieceNum(dto.getPieceNum());
                list.add(pcCutPriceDetailO);
            }
        }
        if (!ObjectUtils.isEmpty(list)){
            BigDecimal maxSeqNo = BigDecimal.ZERO;
            for (PcCutPriceDetailODto t : detailODtos) {
                if (t.getSeqNo().compareTo(maxSeqNo) > 0) {
                    maxSeqNo = t.getSeqNo();
                }
            }
            for (int i = 0; i < list.size(); i++) {
                list.get(i).setSeqNo(maxSeqNo.add(BigDecimal.valueOf(i + 1)));
            }
            costAssignmentMapper.addPcCutPriceDetailO(list);
        }else {
            return ResponseInfo.warn("无差异!");
        }
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 根据序号单条删除
     * @param request
     * @param seqNo
     * @return
     */
    @Override
    public ResponseInfo delBySeqNo(StyleNoToColorRequest request, String seqNo) {
        if (ObjectUtils.isEmpty(request.getStyleNo())||ObjectUtils.isEmpty(request.getStyleColor())){
            return ResponseInfo.error("请选择型体/颜色!");
        }
        UserInfoUtil.UserInfo u = UserInfoUtil.getUserInfo();
        Integer detailExist = costAssignmentMapper.getPcCutPriceDetailExist(request.getStyleNo(), request.getStyleColor(),u.getCompanyId());
        if (detailExist==null||detailExist==0){
            return ResponseInfo.error("该型体冲裁明细不存在!");
        }
        if (!ObjectUtils.isEmpty(request.getCfmFlag())&& Objects.equals(request.getCfmFlag(),DefineEnum.CHECKOUT_FLAG.getValue())){
            return ResponseInfo.error("该型体单价明细已经检核,不能删除!");
        }
        costAssignmentMapper.delBySeqNo(request.getStyleNo(),request.getStyleColor(),u.getCompanyId(),seqNo);
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 根据序号删除
     * @param request
     * @param seqNo
     * @return
     */
    @Override
    public ResponseInfo delBySeqNo2(StyleNoToColorRequest request, String seqNo) {
        if (ObjectUtils.isEmpty(request.getStyleNo())||ObjectUtils.isEmpty(request.getStyleColor())){
            return ResponseInfo.error("请选择型体/颜色!");
        }
        UserInfoUtil.UserInfo u = UserInfoUtil.getUserInfo();
        Integer detailExist = costAssignmentMapper.getPcCutPriceDetail0Exist(request.getStyleNo(), request.getStyleColor(),u.getCompanyId());
        if (detailExist==null||detailExist==0){
            return ResponseInfo.error("该型体手工明细不存在!");
        }
        if (!ObjectUtils.isEmpty(request.getCfmFlag())&& Objects.equals(request.getCfmFlag(),DefineEnum.CHECKOUT_FLAG.getValue())){
            return ResponseInfo.error("该型体单价明细已经检核,不能删除!");
        }
        costAssignmentMapper.delBySeqNo2(request.getStyleNo(),request.getStyleColor(),u.getCompanyId(),seqNo);
        return ResponseInfo.ok("操作成功!");
    }
}
